﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HuynhQuangWebsite.Models;
using System.IO;
using THS.HtmlHelpers;
namespace HuynhQuangWebsite.Controllers
{
    public class ManageServiceController : BaseController
    {
        huynhquangco_websiteEntities ctx = new huynhquangco_websiteEntities();

        //
        // GET: /ManageServices/
        int PageSize = 6;
        public ActionResult IndexService(int page = 1)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var model = new HomeAdminListViewModel();
            IList<Service> services = ctx.Services.OrderByDescending(p => p.ServiceID).ToList();
            model.ServiceList = services.Skip((page-1) * PageSize).Take(PageSize).ToList();
            model.ServiceInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = services.Count() };
            return View(model);
        }
        public ActionResult Paging(int page = 1)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var model = new HomeAdminListViewModel();
            IList<Service> services = ctx.Services.OrderByDescending(p => p.ServiceID).ToList();
            model.ServiceList = services.Skip((page-1) * PageSize).Take(PageSize).ToList();
            model.ServiceInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = services.Count() };
            return PartialView("UCServiceList", model);
        }
        public ActionResult Detail(int id)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            //var model = new HomeAdminListViewModel();
            var Service = (from Services in ctx.Services where Services.ServiceID == id select Services).SingleOrDefault();

            if (Service != null)
            {
                //model.CurrentSevice = Service;
                return View(Service);
            }
            else
            {
                Service = new Service();
                return View(Service);
            }
            //return trang thông báo lỗi
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Detail(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                // if (!IsAuthenticateAdmin())
                //   return RedirectToAction("LogOn", "AdminHome");
                Service service = ctx.Services.Where(p => p.ServiceID == id).SingleOrDefault();

                if (uploadFile != null)
                {
                    String oldImage = service.ServiceImg;
                    String oldThumbImage = service.ServiceImgThumb;
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    String sFileName = Utilities.GenerateImageName(Request, Utilities.VirtualPath, fileName, 1.ToString());
                    string filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    String fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    MakeImagesAndThumbFile(uploadFile.InputStream, filePath, fileThumbPath, 400, 300, 180, 180, 100);
                    service.ServiceImg = Utilities.PhysicalPath + sFileName;
                    service.ServiceImgThumb = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                    //delete image
                    DeleteFile(Request, Utilities.VirtualPath, oldImage);
                    DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);
                }

                UpdateModel(service);
                ctx.SaveChanges();
                ViewData["Msg"] = "Đã cập nhật!";
                return View(service);
                //return RedirectToAction("IndexService");
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗ xẩy ra trong quá trình cập nhật!";
                return View();
            }
        }
        //
        // POST: /FunRingManagement/Create
        public ActionResult Create()
        {
            var model = new Models.Service();
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "ServiceID")]Service service, HttpPostedFileBase uploadFile)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            try
            {
                if (uploadFile != null)
                {
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    String sFileName = Utilities.GenerateImageName(Request, Utilities.VirtualPath, fileName, 1.ToString());
                    string filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    String fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    MakeImagesAndThumbFile(uploadFile.InputStream, filePath, fileThumbPath, 400, 300, 130, 130, 75);
                    service.ServiceImg = Utilities.PhysicalPath + sFileName;
                    service.ServiceImgThumb = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                }
                ctx.AddToServices(service);
                ctx.SaveChanges();
                ViewData["Msg"] = "Đã tạo thành công!";
                return View();
            }
            catch
            {
                return View();

            }
        }
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here
                //if (!IsAuthenticateAdmin())
                //    return RedirectToAction("LogOn", "AdminHome");
                Service service = ctx.Services.Where(p => p.ServiceID == id).SingleOrDefault();
                String oldImage = service.ServiceImg;
                String oldThumbImage = service.ServiceImgThumb;
                var attributes = ctx.ServiceAttributes.Where(attribute => attribute.FK_ServiceID == id).ToList();
                foreach (var attributeItem in attributes)
                {
                    ctx.ServiceAttributes.DeleteObject(attributeItem);
                }
                ctx.Services.DeleteObject(service);
                ctx.SaveChanges();
                DeleteFile(Request, Utilities.VirtualPath, oldImage);
                DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);
                return RedirectToAction("IndexService");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult CreateAttribute(int fk)
        {
            //var model = new HomeAdminListViewModel();
            var model = new ServiceAttribute();
            model.FK_ServiceID = fk;
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateAttribute([Bind(Exclude = "ServiceAttributeID")]ServiceAttribute serviceAttribute)
        {
            
            ctx.AddToServiceAttributes(serviceAttribute);
            ctx.SaveChanges();
            ViewData["Msg"] = "Đã tạo thành công!";
            return RedirectToAction("Detail", "ManageService", new { id = serviceAttribute.FK_ServiceID});
        }
        
        public ActionResult DeleteFromAttribute(int id)
        {
            int fk = 0;
            var attribute = ctx.ServiceAttributes.Where(serviceAttribute => serviceAttribute.ServiceAttributeID == id).SingleOrDefault();
            if (attribute != null)
            {
                fk = (Int32)attribute.FK_ServiceID;
                ctx.ServiceAttributes.DeleteObject(attribute);
                ctx.SaveChanges();
                return RedirectToAction("Detail", "ManageService", new { id = fk });
            }
            else {
                ViewData["Error"] = "có lỗi xảy ra!";
                return RedirectToAction("IndexService", "ManageService");
            }
        }
        
        public ActionResult UpdateToAttribute( int id, string name, int fk)
        {
            var attribute = ctx.ServiceAttributes.Where(serviceAttribute => serviceAttribute.FK_ServiceID == fk && serviceAttribute.ServiceAttributeID == id).SingleOrDefault();
            attribute.ServiceAttributeName = name;
            UpdateModel(attribute);
            ctx.SaveChanges();
            return RedirectToAction("Detail", "ManageService", new { id = attribute.FK_ServiceID });
            
        }
    }
}
